package com.itmk.system.common.service.Impl;

import com.itmk.constants.Constant;
import com.itmk.exception.BusinessException;
import com.itmk.exception.code.BaseResponseCode;
import com.itmk.system.common.service.PublicService;
import com.itmk.system.permission.entity.Permission;
import com.itmk.system.permission.service.PermissionService;
import com.itmk.system.role.entity.Role;
import com.itmk.system.role.service.RoleService;
import com.itmk.system.user.entity.SysUser;
import com.itmk.system.user.service.UserService;
import com.itmk.utils.JwtTokenUtil;
import com.itmk.utils.PasswordUtils;
import com.itmk.vo.req.LoginReqVO;
import com.itmk.vo.resp.LoginRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service

public class PublicServiceImpl implements PublicService {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @Override
    public LoginRespVO loginin(LoginReqVO loginReqVO) {
        SysUser sysUser = userService.getUserByUserName(loginReqVO.getUsername());
//        如果用户不存在
        if (sysUser == null) {
            throw new BusinessException(BaseResponseCode.ACCOUNT_ERROR);
        }
        if(sysUser.getIsEnabled().equals("0")){
            throw new BusinessException(BaseResponseCode.ACCOUNT_NOT_ENABLED);
        }
//        如果用户被冻结
        if (sysUser.getStatus() == 2) {
            throw new BusinessException(BaseResponseCode.ACCOUNT_LOCK_TIP);
        }
        if (!PasswordUtils.matches(sysUser.getSalt(), loginReqVO.getPassword(), sysUser.getPassword())) {
            throw new BusinessException(BaseResponseCode.ACCOUNT_PASSWORD_ERROR);
        }

        Map<String, Object> claims = new HashMap<>();
        //2.获取用户菜单权限
        List<Permission> permissionList = permissionService.getPermissionListByUserId(sysUser.getId());
        //3.获取code字段，返回给前端使用,判断是否有按钮权限用
        List<String> auth = permissionList.stream().filter(item -> item != null).map(item -> item.getName()).collect(Collectors.toList());
//            vo.setAuthList(auth);
        //4.生成菜单数据树
        List<Role> roleList = roleService.findRoleListByUserIdService(sysUser.getId());
        List<String> roles=roleList.stream().filter(item -> item != null && item.getStatus()==1).map(item -> item.getName()).collect(Collectors.toList());
        claims.put(Constant.PERMISSIONS_INFOS_KEY, auth);
        claims.put(Constant.ROLES_INFOS_KEY, roles);
        String accessToken = JwtTokenUtil.getAccessToken(sysUser.getId().toString(), claims);

        log.info("accessToken={}", accessToken);
        Map<String, Object> refreshTokenClaims = new HashMap<>();
        refreshTokenClaims.put(Constant.JWT_USER_NAME, sysUser.getUsername());
        String refreshToken = null;
        if (loginReqVO.getType().equals("1")) {
            refreshToken = JwtTokenUtil.getRefreshToken(sysUser.getId().toString(), refreshTokenClaims);
        } else {
            refreshToken = JwtTokenUtil.getRefreshAppToken(sysUser.getId().toString(), refreshTokenClaims);
        }
        log.info("refreshToken={}", refreshToken);
        LoginRespVO loginRespVO = new LoginRespVO();
        loginRespVO.setUserId(sysUser.getId());
        loginRespVO.setRefreshToken(refreshToken);
        loginRespVO.setAccessToken(accessToken);
        return loginRespVO;
    }
}
